<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/12/21
 * Time: 2:34 PM
 */

namespace App\Api\Controllers\User;



use App\Api\Controllers\BaseController;
use App\Models\QuotaConfig;
use App\Models\Store;
use App\Models\StorePayWay;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CompanyController extends BaseController
{


    public function lists (Request $request)
    {
        try {
            $user = $this->parseToken();//
            $name = $request->get('name', '');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }
            $where = [];
            if ($name) {
                $where['name'] = $name;
            }


            $obj = DB::table('company_rule')->where($where)->orderBy('sort', 'desc');
            $this->t = $obj->count();
            $data = $this->page($obj)->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function edit (Request $request)
    {
        try {
            $user = $this->parseToken();//
            $id = $request->get('id', '');
            $name = $request->get('name', '');
            $quota_date = $request->get('quota_date', '');
            $limit_money = $request->get('limit_money', '');
            $sort = $request->get('sort', '');
            $code = $request->get('code', '');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }
           if ($id) {
               $rs = DB::table('company_rule')->where(['id' => $id])->update([
                    'name' => $name,
                   'quota_date' => $quota_date,
                   'limit_money' => $limit_money,
                   'sort' => $sort,
                   'code' => $code
               ]);
           } else {
               if (DB::table('company_rule')->where(['name' => $name, 'code' => $code])->first()) {
                   return json_encode(['status' => -1, 'message' => $name.'已存在']);
               }
               $rs = DB::table('company_rule')->insert([
                   'name' => $name,
                   'quota_date' => $quota_date,
                   'limit_money' => $limit_money,
                   'sort' => $sort,
                   'code' => $code
               ]);
           }
            if ($rs) {
                return json_encode(['status' => 2, 'message' => '操作成功']);
            } else {
                return json_encode(['status' => -1, 'message' => '操作失败']);
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function b_lists (Request $request)
    {
        try {
            $user = $this->parseToken();//
            $code = $request->get('code', '');
            $mchId = $request->get('mch_id', '');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }
            if (empty($this->company_mod($code, $mchId))) {
                return json_encode(['status' => -1, 'message' => '数据异常']);
            }

            $rule = DB::table('company_rule')->where(['code' => $code])->first();
            if (!$rule) {
                return json_encode(['status' => -1, 'message' => '暂无数据']);
            }
            //$times = $this->times($rule->quota_date);
            $where = [];
            $where['company_code'] = $code;



            $obj = $this->company_mod($code, $mchId)

                //->leftJoin('company_quota_details as quota', 'quota.mch_id', 'company.mch_id')

                ->orderBy('created_at', 'desc');

            $this->t = $obj->count();
            $data = $this->page($obj)->get();





//            foreach ($data as $v) {
//                $where['mch_id'] = $v->mch_id;
//                if ($quotaModel->where('start_date', '>=', $times[0])->where('end_date', '<=', $times[1])->where($where)->first()) {
//                    $v->status = 1;
//                } else {
//                    $v->status = 0;
//                }
//            }

            foreach ($data as $v) {
                $v->quota = 0;
                $v->no_use_quota = 0;
                $v->quota_rate = 0;
                $v->bank_name = "";


//                            DB::connection()->enableQueryLog();


                $obj = $this->company_mod($code, $v->mch_id)->get();
                $storeIds = [];
                foreach ($obj as $vv) {
                    $storeIds[] = $vv->store_id;
                }
                $list =  DB::table('stores')->whereIn('store_id', $storeIds)->select('store_name','store_id')->get();
                $storesName = [];
                foreach ($list as $vvv) {
                    $storesName[] = $vvv->store_name;
                }
                $v->store_name = implode('-', $storesName);



                $details = DB::table('company_quota_details')
                    ->where('start_date', '<=', date('Ymd'))->where('end_date', '>=', date('Ymd'))
                    ->where([
                        'company_rule_id' => $rule->id,
                        'company_code' => $code,
                        'mch_id' => $v->mch_id
                    ])->first();
                $quotaConfig = QuotaConfig::query()->where("mch_id", $v->mch_id)->where("company", $code)->first();
                if(!empty($quotaConfig)){
                    $v->quota_rate = $quotaConfig->quota_rate;
                    $v->bank_name = $quotaConfig->bank_name;
                }
//                var_dump(DB::getQueryLog());
                if ($details) {
                    $v->quota = $details->quota;
                    if ($details->quota - $details->total_amount > 0) {
                        $v->no_use_quota = sprintf('%.2f', $details->quota - $details->total_amount);
                    }
                }
            }



            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function b_quota_config (Request $request)
    {
        try {
            $user = $this->parseToken();//

            $code = $request->get('code', '');
            $mchId = $request->get('mch_id', '');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }


            $rule = DB::table('company_rule')->where(['code' => $code])->first();
            if (!$rule) {
                return json_encode(['status' => -1, 'message' => '暂无数据']);
            }
            $where = [];

            $where['company_code'] = $code;
            $where['mch_id'] = $mchId;

            if ($code == 'easypaya') {
                $rs = DB::table('company_quota_details')->where(['mch_id' => $mchId])->orderBy('id', 'desc')->first();
                if (isset($rs->start_date)) {
                    $rule->quota_date = substr($rs->start_date, -2);
                }
            }

            $times = $this->times($rule->quota_date);

//            DB::connection()->enableQueryLog();
            $nowData = DB::table('company_quota_details')->where('start_date', '>=', $times[0])->where('end_date', '<=', $times[1])->where($where)->first();
//            var_dump(DB::getQueryLog());
            $lastData = DB::table('company_quota_details')->where('start_date', '>=', $times[2])->where('end_date', '<=', $times[3])->where($where)->first();
            $nextData = DB::table('company_quota_details')->where('start_date', '>=', $times[4])->where('end_date', '<=', $times[5])->where($where)->first();

            $data = [
                'last_month' => $lastData,
                'now_month' => $nowData,
                'next_month' => $nextData,
                'last_title' => $times[2].'-'.$times[3],
                'now_title' => $times[0].'-'.$times[1],
                'next_title' => $times[4].'-'.$times[5],
            ];
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function b_quota_add (Request $request)
    {
        try {
            $user = $this->parseToken();//
            $id = $request->get('id', '');
            $name = $request->get('name', '');

            $startDate = $request->get('start_date', '');
            $endDate = $request->get('end_date', '');


            $quota = $request->get('quota', '');
            $mchId = $request->get('mch_id', '');

            $companyRuleId = $request->get('company_rule_id');
            $companyCode = $request->get('company_code');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }

            if (!empty($companyCode)) {
                $companyRuleId = DB::table('company_rule')->where(['code' => $companyCode])->value('id');
            }

            if (empty($companyRuleId)) {
                return json_encode(['status' => -1, 'message' => '缺少参数']);
            }

            if ($id) {
                $rs = DB::table('company_quota_details')->where(['id' => $id])->update([
                    'company_rule_id' => $companyRuleId,
                    'company_code' => $companyCode,
                    'mch_id' => $mchId,
                    'quota'  => $quota,
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                ]);
            } else {
                if (DB::table('company_quota_details')->where([
                    'company_rule_id' => $companyRuleId,
                    'company_code' => $companyCode,
                    'mch_id' => $mchId,
                    'quota'  => $quota,
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                ])->first()) {
                    return json_encode(['status' => -1, 'message' => $name.'已存在']);
                }
                $rs = DB::table('company_quota_details')->insert([
                    'company_rule_id' => $companyRuleId,
                    'company_code' => $companyCode,
                    'mch_id' => $mchId,
                    'quota'  => $quota,
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                ]);
            }
            if ($rs) {
                return json_encode(['status' => 1, 'message' => '操作成功']);
            } else {
                return json_encode(['status' => -1, 'message' => '操作失败']);
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }




    public function import_quota(Request $request)
    {
        try {

            $companyRuleId = $request->get('company_rule_id');
            $companyCode = $request->get('company_code');
            $startDate = $request->get('start_date', '');
            $endDate = $request->get('end_date', '');
            if (empty($_FILES)) {
                $this->status = 2;
                $this->message = '请上传xlsx表格！';
                return $this->format();
            }

            $file_arr = array_shift($_FILES);

            if ($file_arr['error'] !== 0) {

                $this->status = 2;
                $this->message = '请上传xlsx表格！';
                return $this->format();
            }
            $file = $file_arr['tmp_name'];



            $request->validate([
                'file' => 'required|file|mimes:xlsx|max:2048', // 验证文件类型和大小
            ]);

            if ($request->file('file')->isValid()) {
                // 获取文件相关信息
                $file = $request->file('file');
                $extension = $file->getClientOriginalExtension(); // 文件扩展名
                $filename = time() . '.' . $extension; // 新文件名

                // 保存文件
                $file_path = $file->storeAs('/upload/images', $filename); // 保存文件到'uploads'目录
                //阿里云oss
                $AccessKeyId = env('ALIOSS_AccessKeyId');
                $AccessKeySecret = env('ALIOSS_AccessKeySecret');
                $endpoint = env('ALIOSS_endpoint');
                $bucket = env('ALIOSS_bucket');

                $object = $filename;
                try {
                    $content = file_get_contents(public_path() .'/'. $file_path);
                    $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                    $data = $ossClient->putObject($bucket, $object, $content);

                    $url = $data['oss-request-url'];
                    if ($url) {
                        DB::table('company_import_details')->insert([
                            'company_rule_id' => $companyRuleId,
                            'company_code' => $companyCode,
                            'start_date' => $startDate,
                            'end_date' => $endDate,
                            'url' => $url,
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                    //删除本地图片
                    unlink(public_path() .'/'. $file_path);
                } catch (\OSS\Core\OssException $e) {
                    Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
                }
            }


            $excel_data = \App\Common\Excel\Excel::_readExcel($file);


            $rule = DB::table('company_rule')->where(['id' => $companyRuleId])->first();
            if (!$rule) {
                return json_encode(['status' => -1, 'message' => '暂无数据']);
            }

            //$times = $this->times($rule->quota_date);

            $mod = DB::table('company_quota_details');
            $mch = [];
            $success = 0;
            $error = 0;
            DB::beginTransaction();
            try {
                foreach ($excel_data as $k => $v) {
                    if ($k == 0) {
                        continue;
                    }
                    if(empty($v[0])){
                        continue;
                    }
                    $tmp = [
                        'company_rule_id' => $companyRuleId,
                        'company_code' => $companyCode,
                        'mch_id' => trim($v[0]),
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                    ];
                    //判断开始时间是否有在某个额度或等于
                    if (!$mod->where($tmp)->first()
                        && !$mod->where('start_date', '>=', $startDate)->where('end_date', '<=', $endDate)
                            ->where([
                                'company_rule_id' => $companyRuleId,
                                'company_code' => $companyCode,
                                'mch_id' => trim($v[0])
                            ])->first()
                    ) {
                        $mod->insert(array_merge(['quota'  => trim($v[1])], $tmp));
                        $success++;
                    } else {
                        $mch[] = trim($v[0]);
                        $error++;
                    }
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                Log::info("表格未导入：系统错误-",[
                    "error"=> $e->getMessage() . $e->getFile() . $e->getLine(),
                    "data"=>$excel_data
                ]);
            }

            $this->status = 1;
            $this->message = '导入成功';
            return $this->format(['error' => $error, 'success' => $success, 'error_list' => $mch]);


        } catch (\Exception $e) {
            $message = '表格未导入：系统错误：' . $e->getMessage() . $e->getFile() . $e->getLine();
            $this->status = 2;
            $this->message = $message;
            return $this->format();
        }


    }

    public function times ($initDate)
    {
//        if ($initDate <= date('d')) {
//            $lastYear = date('Y', strtotime('-1 month'));
//            $lastMonth = date('m', strtotime('-1 month'));
//            $nowYear = date('Y');
//            $nowMonth = date('m');
//            $nextYear = date('Y', strtotime('+1 month'));
//            $nextMonth = date('m', strtotime('+1 month'));
//        } else {
//            $lastYear = date('Y', strtotime('-2 month'));
//            $lastMonth = date('m', strtotime('-2 month'));
//            $nowYear = date('Y', strtotime('-1 month'));
//            $nowMonth = date('m', strtotime('-1 month'));
//            $nextYear = date('Y');
//            $nextMonth = date('m');
//        }

        if ($initDate <= date('d')) {
            $lastYear = date('Y', strtotime('last day of -1 month'));
            $lastMonth = date('m', strtotime('last day of -1 month'));
            $nowYear = date('Y');
            $nowMonth = date('m');
            $nextYear = date('Y', strtotime('last day of +1 month'));
            $nextMonth = date('m', strtotime('last day of +1 month'));
        } else {
            $lastYear = date('Y', strtotime('last day of -2 month'));
            $lastMonth = date('m', strtotime('last day of -2 month'));
            $nowYear = date('Y', strtotime('last day of -1 month'));
            $nowMonth = date('m', strtotime('last day of -1 month'));
            $nextYear = date('Y');
            $nextMonth = date('m');
        }

        $now_s = strtotime("+$initDate days", strtotime($nowYear.'-'.$nowMonth))- 86400;
        $daysInMonth =  date('t', mktime(0, 0, 0, $nowMonth, 1, $nowYear));//\cal_days_in_month(CAL_GREGORIAN, $nowMonth, $nowYear);
        $now_e = date('Ymd', strtotime("+$daysInMonth days", $now_s) - 86400);

        $last_s = strtotime("+$initDate days", strtotime($lastYear.'-'.$lastMonth))- 86400;
        $lastDaysInMonth = date('t', mktime(0, 0, 0, $lastMonth, 1, $lastYear));//\cal_days_in_month(CAL_GREGORIAN, $lastMonth, $lastYear);
        $last_e = date('Ymd', strtotime("+$lastDaysInMonth days", $last_s) - 86400);

        $next_s = strtotime("+$initDate days", strtotime($nextYear.'-'.$nextMonth))- 86400;
        $nextDaysInMonth = date('t', mktime(0, 0, 0, $nextMonth, 1, $nextYear));//\cal_days_in_month(CAL_GREGORIAN, $lastMonth, $lastYear);
        $next_e = date('Ymd', strtotime("+$nextDaysInMonth days", $next_s) - 86400);

        return [
            date('Ymd', $now_s), $now_e,
            date('Ymd', $last_s), $last_e,
            date('Ymd', $next_s), $next_e
        ];
    }

    public function company_mod ($code, $mchId)
    {

        $where = [];

        $rule = DB::table('company_rule')->where(['code' => $code])->first();

        if (!empty($mchId)) {
            $where = [$rule->mch_num_as => $mchId];
        }
        $mod = DB::table($rule->model)->where($where)->select($rule->mch_num_as.' as mch_id', 'id', 'store_id');
        //error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-company_mod】： ".json_encode([$mod, $rule->model, $where, $rule->mch_num_as])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");

        return $mod;
    }

    public function autoCompany ($store_id, $srore_id_pid, $ways, $total_amount, $i = 0)
    {
        try {
            error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-数据】： ".json_encode([$store_id, $srore_id_pid, $ways, $total_amount, $i])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");
            if ($this->is_quota($store_id) == 2) {
                return $ways;
            }

            //三方通道直接用
            if (in_array($ways->company, ['vbill', 'easypay', 'yinsheng', 'unionpay_merch', 'allinpay'])) { //三方通道不用轮询
                return $ways;
            }
            //没有规则
            $rule = DB::table('company_rule')->where(['code' => $ways->company])->first();
            if (!$rule) {
                return $ways;
            }

            //单笔限额
            if ($total_amount >= $rule->limit_money ) {//
                error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-限额切换】： ".json_encode([$total_amount, $rule->limit_money, $ways->company])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");
                $ways = StorePayWay::where('ways_source', $ways->ways_source)
                    ->where('store_id', $store_id)
                    ->where('status', 1)
                    ->orderBy('sort', 'asc')
                    ->get();
                if (!$ways) {
                    $store_id = "";
                    $srore_id_pid = Store::where('id', $srore_id_pid)
                        ->select('store_id')
                        ->first();
                    if ($srore_id_pid) {
                        $store_id = $srore_id_pid->store_id;
                    }
                    $ways = StorePayWay::where('ways_source', $ways->ways_source)
                        ->where('store_id', $store_id)
                        ->where('status', 1)
                        ->orderBy('sort', 'asc')
                        ->get();
                }
                $i++;
                return $this->autoCompany($store_id, $srore_id_pid, $ways[$i], $total_amount, $i);
            }

            //$times = $this->times($rule->quota_date);

            $source = $this->company_mod($ways->company, '')->where(['store_id' => $store_id])->first();
            error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-company_mod】： ".json_encode([$source])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");

            $nowDate = date('Ymd');

//            DB::connection()->enableQueryLog();
            $details = DB::table('company_quota_details')->where([
                'company_rule_id' => $rule->id,
                'company_code' => $rule->code,
                'mch_id' => $source->mch_id
            ])->where('start_date', '<=', $nowDate)->where('end_date', '>=', $nowDate)->first();
//            $sql=DB::getQueryLog();
//            if (!$details ) {
//                return $ways;
//            }

            if (!$details ) {
                if (in_array($ways->company, ['jiujiang'])) { //
                    return $ways;
                } else {
                    $details = new \stdClass();
                    $details->total_amount = 0;
                    $details->quota = 0;
                }
            }

            error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-数据details】： ".json_encode($details)."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");
            //支付金额+流水金额 是否大于额度
            if ($total_amount + $details->total_amount >= $details->quota) {//
                error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-超额切换】： ".json_encode([$total_amount, $details->total_amount, $details->quota, $ways->company])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");

                $ways = StorePayWay::where('ways_source', $ways->ways_source)
                    ->where('store_id', $store_id)
                    ->where('status', 1)
                    ->orderBy('sort', 'asc')
                    ->get();
                if (!$ways) {
                    $store_id = "";
                    $srore_id_pid = Store::where('id', $srore_id_pid)
                        ->select('store_id')
                        ->first();
                    if ($srore_id_pid) {
                        $store_id = $srore_id_pid->store_id;
                    }
                    $ways = StorePayWay::where('ways_source', $ways->ways_source)
                        ->where('store_id', $store_id)
                        ->where('status', 1)
                        ->orderBy('sort', 'asc')
                        ->get();
                }
                $i++;
                return $this->autoCompany($store_id, $srore_id_pid, $ways[$i], $total_amount, $i);
            }
            return $ways;
        } catch (\Exception $e) {
            error_log(date('Y-m-d H:i:s')." 【轮询通道-切换通道-异常】： ".json_encode([$e->getMessage().$e->getLine()])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");
        }
    }

    public function updateTotalAmount($data)
    {
        try {
            error_log(date('Y-m-d H:i:s')." 【轮询通道-叠加流水-数据】： ".json_encode([$data])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");

            $store_id = $data['store_id'];
            $company = $data['company'];
            $money = $data['total_amount'];
            if ($this->is_quota($store_id) == 2) {
                return ;
            }
            //没有规则
            $rule = DB::table('company_rule')->where(['code' => $company])->first();
            if (!$rule) {
                return '';
            }
            //$source  = $this->company_mod($company, '')->where(['store_id' => $store_id])->first();

            //分店没有配置 找总店
            if (!StorePayWay::where('ways_source', $data['ways_source'])->where('store_id', $store_id)->where('status', 1)->first()) {
                $pid = Store::where('store_id', $store_id)->value('pid');
                $store_id = Store::where('id', $pid)->value('store_id');
            }
            error_log(date('Y-m-d H:i:s')." 【轮询通道-叠加流水-store_id】： ".json_encode([$store_id])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");

            $source  = $this->company_mod($company, '')->where(['store_id' => $store_id])->first();


            $nowDate = date('Ymd');
            $mod     = DB::table('company_quota_details')->where([
                'company_rule_id' => $rule->id,
                'company_code' => $rule->code,
                'mch_id' => $source->mch_id
            ])->where('start_date', '<=', $nowDate)->where('end_date', '>=', $nowDate);
            $details = $mod->first();

            if ($details) {
                $mod->update(['total_amount' => $details->total_amount + $money]);
            }
        } catch (\Exception $e) {
            error_log(date('Y-m-d H:i:s')." 【轮询通道-叠加流水-异常】： ".json_encode([$e->getMessage().$e->getLine()])."\n\n", 3, "/tmp/". 'autoCompany'.date('Ymd').".log");
        }
    }


    public function msg ()
    {

    }

    public function store_list (Request $request)
    {
        $mchId = $request->get('mch_id');
        $companyCode = $request->get('company_code');
        $obj = $this->company_mod($companyCode, $mchId)->get();
        $storeIds = [];
        foreach ($obj as $v) {
            $storeIds[] = $v->store_id;
        }
        $list =  DB::table('stores')->whereIn('store_id', $storeIds)->select('store_name','store_id')->get();
        $this->status = 1;
        $this->message = '成功';
        return $this->format($list);
    }

    public function is_quota ($store_id)
    {
        try {
            return DB::table('stores')->where(['store_id' => $store_id])->value('is_quota');
        } catch (\Exception $e) {
            return 2;
        }
    }


    public function import_list (Request $request)
    {
        try {
            $user = $this->parseToken();//
            $companyCode = $request->get('company_code');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }

            $obj = Db::table('company_import_details')->where(['company_code' => $companyCode])->leftJoin('company_rule', 'company_rule_id', 'company_rule.id')->orderBy('created_at', 'desc');

            $this->t = $obj->count();
            $data = $this->page($obj)->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function import_quota_all (Request $request)
    {
        try {

            if (empty($_FILES)) {
                $this->status = 2;
                $this->message = '请上传xlsx表格！';
                return $this->format();
            }

            $file_arr = array_shift($_FILES);

            if ($file_arr['error'] !== 0) {

                $this->status = 2;
                $this->message = '请上传xlsx表格！';
                return $this->format();
            }
            $file = $file_arr['tmp_name'];


//            $request->validate([
//                'file' => 'required|file|mimes:xlsx|max:100000', // 验证文件类型和大小
//            ]);

            if ($request->file('file')->isValid()) {
                // 获取文件相关信息
                $file = $request->file('file');
                $extension = $file->getClientOriginalExtension(); // 文件扩展名
                $filename = time() . '.' . $extension; // 新文件名

                // 保存文件
                $file_path = $file->storeAs('/upload/images', $filename); // 保存文件到'uploads'目录
                //阿里云oss
                $AccessKeyId = env('ALIOSS_AccessKeyId');
                $AccessKeySecret = env('ALIOSS_AccessKeySecret');
                $endpoint = env('ALIOSS_endpoint');
                $bucket = env('ALIOSS_bucket');

                $object = $filename;
                try {
                    $content = file_get_contents(public_path() .'/'. $file_path);
                    $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                    $data = $ossClient->putObject($bucket, $object, $content);

                    $url = $data['oss-request-url'];
                    if ($url) {
                        DB::table('company_import_details')->insert([
                            'types' => 2,
                            'url' => $url,
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                    //删除本地图片
                    unlink(public_path() .'/'. $file_path);
                } catch (\OSS\Core\OssException $e) {
                    Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
                }
            }

            $excel_data = \App\Common\Excel\Excel::_readExcel($file);

            $mod = DB::table('company_quota_details');
            $mch = [];
            $success = 0;
            $error = 0;
            $companyRuleMod = DB::table('company_rule');
//            var_dump(DB::table('company_rule')->where(['code' => 'cib'])->value('id'));

            DB::beginTransaction();
            try {
                foreach ($excel_data as $k => $v) {
                    if ($k == 0) {
                        continue;
                    }
                    if(empty($v[0])){
                        continue;
                    }
                    $companyCode = trim($v[1]);
                    $startDate = trim($v[2]);
                    $endDate = trim($v[3]);
                    $companyRuleId = DB::table('company_rule')->where(['code' => $companyCode])->value('id');

                    $tmp = [
                        'company_rule_id' => $companyRuleId,
                        'company_code' => $companyCode,
                        'mch_id' => trim($v[0]),
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                    ];

                    //判断开始时间是否有在某个额度或等于

                    if (!DB::table('company_quota_details')->where($tmp)->first()
                        && !DB::table('company_quota_details')->where('start_date', '>=', $startDate)->where('end_date', '<=', $endDate)
                            ->where([
                                'company_rule_id' => $companyRuleId,
                                'company_code' => $companyCode,
                                'mch_id' => trim($v[0])
                            ])->first()
                    ) {
                        Log::info("company_quota_details-import",$v);
                        DB::table('company_quota_details')->insert(array_merge(['quota'  => trim($v[4])], $tmp));
                        $success++;
                    } else {
                        $mch[] = [$companyCode, trim($v[0])];
                        $error++;
                    }
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                Log::info("import-all",[
                    "error"=> $e->getMessage() . $e->getFile() . $e->getLine(),
                    "data"=>$excel_data
                ]);
            }



            $this->status = 1;
            $this->message = '导入成功';
            return $this->format(['error' => $error, 'success' => $success, 'error_list' => $mch]);


        } catch (\Exception $e) {
            $message = '表格未导入：系统错误：' . $e->getMessage() . $e->getFile() . $e->getLine();
            $this->status = 2;
            $this->message = $message;
            return $this->format();
        }


    }

    public function exportToExcel($filename, $s_array, $tileArray = [], $dataArray = [])
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);

        $fp = fopen($filename, 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($dataArray as $item) {
            if(!empty($item['mch_id'])){
                $item['mch_id'] = $item['mch_id']. "\t";
            }
            $index++;
            fputcsv($fp, $item);
        }

        fclose($fp);


        // 保存文件

        //阿里云oss
        $AccessKeyId = env('ALIOSS_AccessKeyId');
        $AccessKeySecret = env('ALIOSS_AccessKeySecret');
        $endpoint = env('ALIOSS_endpoint');
        $bucket = env('ALIOSS_bucket');
        $file_path = '/'.$filename;
        $object = $filename;
        try {
            $content = file_get_contents(public_path() .'/'. $file_path);
            $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
            $data = $ossClient->putObject($bucket, $object, $content);

            $url = $data['oss-request-url'];

            if ($url) {
                DB::table('company_import_details')->insert([
                    'types' => 2,
                    'url' => $url,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                return $url;
            }
            return '';
            //删除本地图片
            unlink(public_path() .'/'. $file_path);
        } catch (\OSS\Core\OssException $e) {
            return '';
            Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
        }

    }

    public function download_mch (Request $request)
    {
        try {
            $code = $request->get('code');
            if ($code) {
                $code = explode(',',$code);
                $rule = DB::table('company_rule')->whereIn('code', $code)->get();
            } else {
                $rule = DB::table('company_rule')->get();
            }


            $tmp = [];
            $companyList = [];
            foreach ($rule as $v) {
                $mchList = $this->company_mod($v->code, '')->get();
                $companyList[] = $v->name;
                $times = $this->times($v->quota_date);
                foreach ($mchList as $mv) {
                    $isConfig = DB::table('company_quota_details')
                        ->where('start_date', '>=', $times[0])->where('end_date', '<=', $times[1])
                        ->where([
                            'company_rule_id' => $v->id,
                            'company_code' => $v->code,
                            'mch_id' => $mv->mch_id
                        ])->first();
                    //判断是否开启
                    $isQuota = DB::table('stores')->where(['store_id' => $mv->store_id])->value('is_quota');
                    if (!$isConfig && $isQuota == 1) {
                        $tmp[] = [
                            'mch_id' => $mv->mch_id,
                            'store_id' => $mv->store_id,
                            'code' => $v->code,
                            'start_date' => $times[0],
                            'end_date' => $times[1],
                            'quota' => 0,
                        ];
                    }
                }
            }

            //添加新字段
            if ($tmp) {
                foreach ($tmp as &$t) {
                    $storeInfo = DB::table('stores')->select('store_name', 'user_id')->where(['store_id' => $t['store_id']])->first();
                    $username = DB::table('users')->where(['id' => $storeInfo->user_id])->value('name');
                    $t['store_id'] = $storeInfo->store_name;
                    $t['user_id'] = $username;
                }
            }

            $filename = date('Y-m-d').'-未配置额度.csv';
            $s_array = ['通道条件：' . implode('-', $companyList)];
            $tileArray = ['商户号', '商户', '标识', '开始时间','结束时间','额度','代理商名称'];
            $url = $this->exportToExcel($filename,$s_array,$tileArray, $tmp);
            if ($url) {
                DB::table('company_import_details')->insert([
                    'types' => 3,
                    'url' => $url,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                $this->status = 1;
                $this->message = '下载成功';
                return $this->format(['url' => $url]);
            }
            $message = '下载失败';
            $this->status = 2;
            $this->message = $message;
            return $this->format();
        } catch (\Exception $e) {
            $message = '系统错误：' . $e->getMessage() . $e->getFile() . $e->getLine();
            $this->status = 2;
            $this->message = $message;
            return $this->format();
        }
    }

    //易生联合收单获取额度
    public function easypayGetQuota(Request $request)
    {
        try {
            $ids = explode(',', $request->get('mch_id'));
            $base = (new \App\Api\Controllers\EasyPay\MerchantController());
            $ret = false;

            $easypay_configs = DB::table('easypay_configs')->where("config_id","1234")->first();
            $private_key = $easypay_configs->private_key;
            $t = [];
            $companyRuleId = DB::table('company_rule')->where(['code' => 'easypaya'])->value('id');
            foreach ($ids as $v) {
//                $private_key = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc1mku1mtfTc1vZM9z3TkRMZ9SaKP+6MdoQhjDHB9vJUOuG2Jnegej4gtzcm8MVYomV1azJMtCbPq4PN9aHegH13JthvrUPR3nAKp8AUp9Fh47ded//snNyAf7C7o8xKN5e7n89ROwacCAL2QDno76ngXzQQVj1TxY9pBdekZ03ezuDk1sv/u4FBlW8kRyaVdqyl4FdvP+EEljDe8gGxRikLyb3cK1B6G7w2BXgM/svft5SOoiqStx2XvgHRrFRB5w96TdoKNH9yxHU2clMJiz+5cej1VL6OHZspuY3cnPyJtyS+weYjDT+COLLBUe9UwbOV15DXDNpBLd34W4GiqtAgMBAAECggEAYaVwmVOwSAblp7wJGScb16OggStbJ2MAe93jEt7Yh1eZGrY7/xbP2O3smTUfBHvhZlusRB7dWf8F3l0v5iiGhRNTT/PhCPEARAl7G3emS9jQe869kkgslq06ose7bQg0i3dH5cEkQAqnameXClXWyRxHshrCY1SonO7uFPUDFtD2Z9GHu6dOWkOHfX7UETHV5/NTSqvner5M2YNsV/5To87zrmaeeNyvu91JgJSYofTD8IcMyhxcswxB9F3ECP7nulLDdCV+9mvE9zO0i4mPBxYb++87J0pu35TN9OY+gpiCK3Ed0gDqvvkTiCQEFu6y7OiqsQwy03CE5hAwWZR2YQKBgQDdb6e7+FWJSr9fIknfvZPPtKmbEkMHP1RYnVo3pmuVm14Z3UmostiSBRPMfVjeOX0N82SONM9P+1v9SDgSK3pL8rlk9Hx6D5KI7uj2IMtTVt00pO31KtxDLmXfgapDbWHK1RGEn1PDrnKYy5yOKJ8n0Wgp4lVEPIBN6uIud0A9iQKBgQC1UXdhEXFETyqEYWb9OnWbBjiVIw3D2/qW5c+WQGsHYdMEImC/0oTWIH9fKd4Azf26JjZ9nQvs5VcijJP6BXbGPqir5NgGVkwCj33PoNg4dDgIVE4BYaSp//7B6jCi5QiRTzCSOmUSkZ5L1Kz4SNEDe9r0MpLhxrsAzmR9aEJ/BQKBgHI71Ks63F2cSwd39+ZNtYA0cj7Gd/+4IvooCs+kseGXKj9rkkFOKj2CEwmuLHdP7vyQcHKQOdbIFFegtxRgi5G8oPm8yq5pdC3iGhpHJr1SlYFACGYu+zxJJlLcYIqyVf2+V3A0hZDwYLwEZjpMKHbxJ6xbz6MJFyObJZ3U9TYJAoGANXoGjJF5Z501u/+CQZN5VjSagZnqGGcL3G+BLx5msrGua9y7zjeHyCOjjWyqtnAKsllM3vVvq/nkHiN6DVaJNmUKmFARSqUvG944TAFzZAsa75H1w8CJsT34ZDbvC0wjn7/MYoRohPZ/ynu6XCwVwUJJTJaR7ZcQVmeJCdezLQUCgYEAszix6V9oL80Clb1nMwIly6I78+pcFKyk82yXxvySb6XPJvgoasbz9xYIeKlPyy6r8Aj/ujz5GVtDtkE6n6bsjekCdnUKUY3uTvFAX+YGQkuZnaPoisELJFI2Hal22tNnJyCOYh//AGAiHYpHNUKD4hsKBb45MhK1xwvTHpuLkdc=';
//                $reqId = '531000023045074';
//                $private_key = DB::table('easypaya_stores')->where(['termMercode' => $v])->first();
                $reqId = 'ORG000000001897';
                if (!$private_key) {
                    continue;
                }
                $actRet = json_decode($base->act_query(['mchtCode' => $v, 'reqId' => $reqId], $private_key), true);
                Log::channel("easypay")->info("easypayGetQuota",[
                    "res"=>$actRet
                ]);
//                $actRet = json_decode('{"data":{"marketingDetailList":[{"accumulationType":"1","activityId":1756,"beginDate":"2025-02-16T00:00:00","billingCycle":"0","businessAmount":300.00,"businessModel":"1","businessSceneCode":"ALL;UnionPromoCNP,UnionPromoCP","cardIssuerCode":"ALL","cardType":"XXXX","countCycle":"0","createBy":"UMP","createDatetime":"2025-02-15T18:35:13","discountType":"2","discountValue":0.30,"endAmount":999999.00,"endDate":"2025-03-15T23:59:59","instalNum":"ALL","marketingQuotaUsed":31.74,"mchtCode":"531000020795644","payAbilityCode":"WeChat,AliPay;UnionPay","payMethodCode":"ALL;ALL","quotaId":6664085,"registrationId":13362250,"registrationLevel":4,"registrationStatus":"1","startAmount":0.01,"updateDatetime":"2025-02-15T18:35:15"},{"accumulationType":"1","activityId":741,"beginDate":"2025-01-04T18:00:00","billingCycle":"0","businessAmount":600.00,"businessModel":"1","businessSceneCode":"ALL;UnionPromoCNP,UnionPromoCP","cardIssuerCode":"ALL","cardType":"XXXX","countCycle":"0","createBy":"UMP","createDatetime":"2025-01-04T17:15:00","discountType":"2","discountValue":0.30,"endAmount":999999.00,"endDate":"2025-02-15T23:59:59","instalNum":"ALL","marketingQuotaUsed":600.00,"mchtCode":"531000020795644","payAbilityCode":"WeChat,AliPay;UnionPay","payMethodCode":"ALL;ALL","quotaId":6161397,"registrationId":12914367,"registrationLevel":4,"registrationStatus":"1","startAmount":0.01,"updateDatetime":"2025-01-04T17:15:00"}],"retCode":"000000","retMsg":"处理成功"},"success":true,"sysRetCode":"000000","sysRetMsg":"SUCCESS"}', true);

                if(!isset($actRet["data"])){
                    $actRet["data"]=$actRet['rspBody'];
                }

                if (isset($actRet['data']['marketingDetailList']) && !empty($actRet['data']['marketingDetailList'])) {
                    foreach ($actRet['data']['marketingDetailList'] as $vv) {
                        if ($vv['registrationStatus'] == 1) {
                            $quota = $vv['businessAmount'] - $vv['marketingQuotaUsed'];
                            if (date('m') != date('m', strtotime($vv['beginDate']))) {
                                continue;
                            }
                            if ($quota == 0) {
                                continue;
                            }
                            $ret = true;
                            $startDate = date('Ymd', strtotime($vv['beginDate']));
                            $endDate = date('Ymd', strtotime($vv['endDate']));
//                            $companyRuleId = DB::table('company_rule')->where(['code' => 'easypaya'])->value('id');
                            $quotaConfig = QuotaConfig::query()->where("mch_id", $v)->where("company", "easypaya")->first();
                            $tmp = [
                                'company_rule_id' => $companyRuleId,
                                'company_code' => 'easypaya',
                                'mch_id' => $v,
                                'start_date' => $startDate,
                                'end_date' => $endDate,
                                "quota_rate" => empty($quotaConfig) ? 0 : $quotaConfig->quota_rate,
                                "bank_name" => empty($quotaConfig) ? "" : $quotaConfig->bank_name
                            ];
                            $t[] = array_merge($tmp, ['quota'  => $quota]);
                            //判断开始时间是否有在某个额度或等于
//                            if (!DB::table('company_quota_details')->where($tmp)->first()
//                                && !DB::table('company_quota_details')->where('start_date', '>=', $startDate)->where('end_date', '<=', $endDate)
//                                    ->where([
//                                        'company_rule_id' => $companyRuleId,
//                                        'company_code' => 'easypaya',
//                                        'mch_id' => $v
//                                    ])->first()
//                            ) {
//                                DB::table('company_quota_details')->insert(array_merge(['quota'  => $quota], $tmp));
//                            }
                        }
                    }
                }
            }
            if ($ret) {
                return json_encode(['status' => 1, 'message' => '获取成功', 'data' => $t]);
            } else {
                return json_encode(['status' => 0, 'message' => '获取失败']);
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function easypayGetConfig(Request $request)
    {
        try {
            $user = $this->parseToken();//

            $code = $request->get('code', '');
            $mchId = $request->get('mch_id', '');
            if ($user->pid != 0) {
                return json_encode(['status' => -1, 'message' => '暂无权限']);
            }

            $rule = DB::table('company_rule')->where(['code' => $code])->first();
            if (!$rule) {
                return json_encode(['status' => -1, 'message' => '暂无数据']);
            }
            $where = [];

            $where['company_code'] = $code;
            $where['mch_id'] = $mchId;
            $lastData = $nowData = $nextData = $lastTitle = $nowTitle = $nextTitle = '';
            $result = DB::table('company_quota_details')->where($where)->orderBy('end_date', 'desc')->limit(3)->get();

            foreach ($result as $k => $v) {
                if ($k == 2) {
                    $lastTitle = $v->start_date.'-'.$v->end_date;
                    $lastData = $v;
                }
                if ($k == 1) {
                    $nowTitle = $v->start_date.'-'.$v->end_date;
                    $nowData = $v;
                }
                if ($k == 0) {
                    $nextTitle = $v->start_date.'-'.$v->end_date;
                    $nextData = $v;
                }
            }
            $data = [
                'last_month' => $lastData,
                'now_month' => $nowData,
                'next_month' => $nextData,
                'last_title' => $lastTitle,
                'now_title' => $nowTitle,
                'next_title' => $nextTitle,
            ];
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


}